﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;

namespace AppLab.Core
{
    public class TextWriterLogListener : LogListener
    {
        private TextWriter writer;
        private string fileName;

        public TextWriterLogListener(string file)
        {
            fileName = file;
        }

        public override void WriteLine(string level, string text)
        {
            if (EnsureWriter())
            {
                writer.WriteLine(String.Format("[{0}][{1}] {2}",
                    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), level, text));
            }
        }

        public override void Flush()
        {
            if (this.writer != null)
            {
                this.writer.Flush();
            }
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                this.Close();
            }
        }

        protected override void Close()
        {
            if (this.writer != null)
            {
                this.writer.Close();
            }
            this.writer = null;
        }

        private bool EnsureWriter()
        {
            bool flag = true;
            if (this.writer == null)
            {
                flag = false;
                if (this.fileName == null)
                {
                    return flag;
                }

                string fullPath = Path.GetFullPath(this.fileName);
                string directoryName = Path.GetDirectoryName(fullPath);
                string fileName = Path.GetFileName(fullPath);
                for (int i = 0; i < 2; i++)
                {
                    try
                    {
                        this.writer = new StreamWriter(fullPath, true, Encoding.UTF8, 0x1000);
                        flag = true;
                        break;
                    }
                    catch (IOException)
                    {
                        //fileName = Guid.NewGuid().ToString() + fileName;
                        //fullPath = Path.Combine(directoryName, fileName);
                        Thread.Sleep(500);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        break;
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }
                if (!flag)
                {
                    this.fileName = null;
                }
            }
            return flag;
        }


    }
}
